import timLogin from '@/utils/timLogin.js' // 导入tim 登录
import firendTree from './components/firendTree.vue'
import formatMessageDate from '@/utils/commen/imTimeFormat.js'

import {share} from '@/utils/common-api.js' // 导入分享方法

export default {
  components: {
    firendTree
  },
  data() {
    return {
      keyword: '',
      selectfriend: [{
        name: '全部',
        id: 0,
        check: true
      }, {
        name: '今日',
        id: 1,
        check: false
      }, {
        name: '本月',
        id: 2,
        check: false
      }],
      //我的邀请人
      result: {
        PageIndex: 1,
        PageSize: 20,
        selectType: 0,
        isEnd: false,
        loading: false,
        status: 'loading',
        data: []
      },
      // 服务商、群信息
      res: {
        myIMGroup: null,
        parentIMGroup: null,
        parentUser: null,
        serviceProvider: null
      },
      myIMGroup: [],
      groupInfo: null,
      groupInfoMe: null,
      showPopup: false, // 添加好友弹窗
      showPage: false,
      defaultAvatar: 'https://files.yzsheng.com/AccountDefaultImg/defaultImg.png'
    }
  },
  filters: {
    formatMessage(data) {
      let text = ''
      if(!data.im) {
        return ''
      }
      // 如果未读数量大于0 则添加进文本
      if(data.im.unreadCount > 0) {
        text += `[${data.im.unreadCount}条] `
      }
      // 如果发最后一条消息的人有昵称 则添加进文本
      if(data.im.lastMessage.nick) {
        text += `${data.im.lastMessage.nick}: `
      }
      // 最后一条消息内容
      if(data.im.lastMessage.nick) {
        text += `${data.im.lastMessage.messageForShow}`
      }
      return text
    },
    formatDate(data) {
      return data ? formatMessageDate(data * 1000, false) : ''
    }
  },
  computed: {
    timUserInfo() {
      return this.$store.state.timUserInfo
    }
  },
  onLoad() {
    // this.GetMyFriendList(0)
    // uni.showLoading({
    //   title: '加载中'
    // })
    // 登录tim
    if(this.$store.state.isSDKReady) {
      if(!this.timUserInfo.isService) {
        this.GetUserServiceProvider()
        this.getMyGoodFriendList({
          user_Id: this.$store.state.timUserInfo.userId
        })
      } else {
        this.GetServiceProvidersIMGroup()
        this.getMyGoodFriendList({
          user_Id: this.$store.state.timUserInfo.userId
        })
      }
    } else {
      timLogin(() => {
        if(!this.timUserInfo.isService) {
          this.GetUserServiceProvider()
          this.getMyGoodFriendList({
            user_Id: this.$store.state.timUserInfo.userId
          })
        } else {
          this.GetServiceProvidersIMGroup()
          this.getMyGoodFriendList({
            user_Id: this.$store.state.timUserInfo.userId
          })
        }
      })
    }

  },
  async onShow() {
    try{
      if(this.showPage && this.$store.state.isSDKReady) {
        timLogin(() => {
          this.res = {
            myIMGroup: null,
            parentIMGroup: null,
            parentUser: null,
            serviceProvider: null
          }
          this.myIMGroup = []
          this.groupInfo = null
          this.groupInfoMe = null
          let userinfo = uni.getStorageSync('Ztc_C_USER_INFO')
          if(!this.timUserInfo.isService) {
            this.GetUserServiceProvider()
            this.getMyGoodFriendList({
              user_Id: this.$store.state.timUserInfo.userId
            }, true)
          } else {
            this.GetServiceProvidersIMGroup()
            this.getMyGoodFriendList({
              user_Id: this.$store.state.timUserInfo.userId
            }, true)
          }
        })
      }

      if(this.timUserInfo.isService) {
        // let group = await this.getGroupProfile(this.groupInfo)
        // let groupMe = await this.getGroupProfile(this.groupInfoMe)
        // this.groupInfo = group
        // this.groupInfoMe = groupMe
        let arr = this.groupInfo.map(item => {
          return this.getGroupProfile(item)
        })
        Promise.all(arr).then(data => {
          this.myIMGroup = data
        })
      }
      if(this.showPage) {
        if(this.timUserInfo.isService) {
          this.GetServiceProvidersIMGroup()
        } else {
          this.GetUserServiceProvider()
        }
      }
    }catch(e){
      //TODO handle the exception
    }
  },
  onReachBottom() {
    this.getMyGoodFriendList({
      user_Id: this.$store.state.timUserInfo.userId
    })
  },
  methods: {
    // 计算总共有多少页
    pageCount (totalnum,limit){
      return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0
    },
    //获取服务商及上级信息
    async GetUserServiceProvider() {
      try {
        let {data, code} = await this.$api.chat.GetUserServiceProvider()
        data.myIMGroup = data.myIMGroup || []
        let myIMGroup = data.myIMGroup.map(item => {
          item.im = null
          return item
        })
        delete data.myIMGroup
        this.showPage = true
        for(let i in data) {
          if(data[i]) {
            data[i].im = null
          }
        }
        this.res = data
        this.myIMGroup = myIMGroup

        let arr = myIMGroup.map(item => {
          return this.getGroupProfile(item)
        })
        Promise.all(arr).then(data => {
          console.log(data)
          this.myIMGroup = data
        })

        this.getConversationProfile()

      } catch (err) {
      }
    },
    // 获取服务商群
    async GetServiceProvidersIMGroup() {
      try{
        let res = await this.$api.chat.GetServiceProvidersIMGroup({
          in_Group_Type: 10,
          userId: this.$store.state.timUserInfo.userId
        })
        // if(res.data) {
        //   let group = await this.getGroupProfile(res.data[0])

        //   this.showPage = true
        //   let groupMe = res.data[1] ? await this.getGroupProfile(res.data[1]) : null
        //   this.groupInfo = group
        //   this.groupInfoMe = groupMe
        // } else {
        //   this.groupInfo = res.data
        // }
        this.showPage = true
        if(res.data) {
          let groupInfo = res.data.map(item => {
            item.im = null
            return item
          })
          this.groupInfo = groupInfo

          let arr = res.data.map(item => {
            return this.getGroupProfile(item)
          })
          Promise.all(arr).then(data => {
            this.groupInfo = data
          })
        }
      }catch(e){
      }
    },
    // 获取我的好友
    async getMyGoodFriendList(data, init) {
      let res = this.result
      if(init) {
        res.loading = false
        res.PageIndex = 1
        res.isEnd = false
      }
      if (res.loading || res.isEnd) {
        return false
      }
      res.loading = true
      this.result = res

      try{
        let resData = await this.$api.chat.GetMyGoodFriendList({
          ...data,
          pageIndex: res.PageIndex,
          pageSize: res.PageSize,
          selectType: res.selectType,
          keyWords: this.keyword
        })
        resData = resData.data
        // 数量统计
        let selected = this.selectfriend
        selected[0].number = resData.allCount
        selected[1].number = resData.dayCount
        selected[2].number = resData.monthCount
        this.selectfriend = selected
        let list = resData.list.list.map(item => {
          item.selected = false
          item.first = true
          return item
        })

        if (res.PageIndex === 1) {
          res.data = []
        }

        // 如果返回数据列表为空，或者当前页数大于总页数代表已经到最后一页了
        if(list.length <= 0 || res.PageIndex >= this.pageCount(resData.list.total, res.PageSize)) {
          res.isEnd = true
          res.status = 'nomore'
        }

        if (list.length > 0) {
          res.data = res.data.concat(list)
          res.PageIndex = res.PageIndex + 1
        }
        res.loading = false
        this.result = res
        uni.hideLoading()
      }catch(e){
        uni.hideLoading()
      }
    },
    // 我邀请的人切换
    allnumClick(item, index) {
      let listbox = [] //暂存赋值
      this.selectfriend.forEach((item, i) => {
        if (i === index) {
          if (item.check === false) {
            item.check = true
            this.result.selectType = item.id
          } else {}
        } else {
          item.check = false
        }
        listbox.push(item)
      })
      this.selectfriend = listbox

      uni.showLoading({
        title: '加载中'
      })
      this.getMyGoodFriendList({
        user_Id: this.$store.state.timUserInfo.userId
      }, true)
    },
    //fanhui
    backclick() {
      uni.navigateBack({
        delta: 1
      })
    },
    //服务商信息
    bussbtnclick() {
      uni.navigateTo({
        url: '/pages_userModule/mybussMessage/mybussMessage?id=' + this.serviceInfo.accountid
      })
    },
    onJumpChat(data, type = 'C2C') {
      let id = ''
      let name = ''
      if(type === 'GROUP') {
        id = data.id
        if(data.group_name) {
          name = `&name=${encodeURIComponent(data.group_name)}`
        }
      } else {
        id = data.accountid || data.uid
        name = data.serviceName || data.userName
        if(name){
          name = `&name=${encodeURIComponent(name)}`
        } else {
          name = '&name='
        }
      }
      uni.navigateTo({
        url: `/pages_chat/chat/chat?id=${id}&type=${type}${name}`
      })
    },
    // 跳转群发
    onJumpMass() {
      uni.navigateTo({
        url: '/pages_chat/mass/massAide/massAide'
      })
    },
    // 点击搜索
    onSearch() {
      if(!this.keyword) return false
      uni.showLoading({
        title: '加载中'
      })
      this.getMyGoodFriendList({
        user_Id: this.$store.state.timUserInfo.userId,
        keyWords: this.keyword
      }, true)
    },
    // 点击搜索框清楚
    onClear() {
      uni.showLoading({
        title: '加载中'
      })
      this.getMyGoodFriendList({
        user_Id: this.$store.state.timUserInfo.userId
      }, true)
    },
    // 获取会话信息
    getConversationProfile() {
      for(let i in this.res){
        let type = 'C2C'
        let id = ''
        if(i === 'myIMGroup' || i === 'parentIMGroup') {
          type = 'GROUP'
          id = this.res[i].id
        } else {
          id = this.res[i].accountid || this.res[i].uid
        }

        this.tim.getConversationProfile(type + id).then(imResponse => {
          let im =  imResponse.data.conversation
          if(type === 'GROUP' && im.lastMessage.fromAccount){
            this.tim.getUserProfile({
              userIDList: [im.lastMessage.fromAccount]
            }).then(userinfo => {
              im.lastMessage.nick = userinfo.data[0].nick
              data.im = im
              this.res[i].im = im
            }).catch(userinfoError => {
              this.res[i].im = im
            })
          } else {
            this.res[i].im = im
          }
        })
      }
    },
    // 获取群资料
    getGroupProfile(data) {
      return new Promise((resolve, reject) => {
        // 获取群资料
        this.tim.getConversationProfile(`GROUP${data.id}`).then(imResponse => {
          let im = imResponse.data.conversation
          if(im.lastMessage.fromAccount) {
            this.tim.getUserProfile({
              userIDList: [im.lastMessage.fromAccount]
            }).then(userinfo => {
              im.lastMessage.nick = userinfo.data[0].nick
              data.im = im
              resolve(data)
            }).catch(userinfoError => {
              if(data){
                resolve(data)
              } else {
                reject(userinfoError)
              }
            })
          } else {
            data.im = im
            resolve(data)
          }
        }).catch(imError => {
          if(data){
            resolve(data)
          } else {
            reject(imError)
          }
        })
      })
    },
    // 点击企业成员
    onClickMemberList() {
      uni.navigateTo({
        url: '/pages_userModule/enterpriseMember/enterpriseMember'
      })
    },
    // 查看全部群
    onCheckAllGroup() {
      uni.navigateTo({
        url: `/pages_userModule/myGroup/myGroup?id=${this.groupInfo.id}`
      })
    },
    // 跳转群聊
    onJumpChatGroup(groupInfo) {
      let name = groupInfo.im ? groupInfo.im.groupProfile.name : groupInfo.group_name
      uni.navigateTo({
        url: `/pages_chat/chat/chat?id=${groupInfo.id}&type=GROUP&name=${encodeURIComponent(name)}`
      })
    },
    // 点击添加
    onClickAddFriend() {
      this.showPopup = true
    },
    // 选择添加方式
    onChangeAddFriend(type) {
      this.showPopup = false
      if(type === 'weixin') {
        let params = {
          title: '在吗？100%纯羊毛等你来薅哟~',
          summary: '送1000元购车抵用券+39元免费洗车券！点击领取吧',
          href: 'https://files.yzsheng.com/shareH5/Qmc_Client_H5/index.html?code=' + this.timUserInfo.invitecode, //这地址太长了，就省略了
          imageUrl: 'https://files.yzsheng.com/client/me/img/logo.png',
        }
        share({
          scene: 'WXSceneSession',
          type: 0,
          ...params
        }, () => {

        })
      } else {
        uni.navigateTo({
          url: '/pages_userModule/mobileContacts/mobileContacts?inviteCode=' + this.timUserInfo.invitecode
        })
      }
    },
    onClickDisabled() {
      uni.showToast({
        icon: 'none',
        title: '敬请期待'
      })
    },
    // 跳转服务商详情
    onCheckBussInfo(data) {
      uni.navigateTo({
        url: `/pages_userModule/mybussMessage/mybussMessage?id=${data.accountid}`
      })
    }
  },
  onTabItemTap(e) {
    // console.log(e.index)
    if(e.index === 2 && !uni.getStorageSync('token')){
      uni.setStorage({
        key: 'launchFlag',
        data: false,
      })
      // uni.hideTabBar()
      uni.redirectTo({
        url: '/pages_logins/login/login',
        success: () => {
          let t = setTimeout(() => {
            uni.hideLoading()
            clearTimeout(t)
          }, 300)
        }
      })
    }
  }
}
